//
//  JZHSecondViewController.m
//  极致荟
//
//  Created by mac on 14-4-8.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHSecondViewController.h"
#import "THGridMenuItem+BookItem.h"

#import "JZHProductDetailsViewController.h"
#import "JZHSecondTableViewCell.h"
#import "JZHDovConViewController.h"
#import "ImageCache.h"
#import "JZHBlackCardDetailViewController.h"
#import "JZHNoProductViewController.h"
@interface JZHSecondViewController ()
{
    UIButton *leftButton;
    JZHCEView *ceview;
   __block int mypage;//页数；
    __block NSString *mykeyword;//搜索数据
    __block int mycateId;//侧边栏id
    
}
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet SuperUIScrollView *scorll;
@end

@implementation JZHSecondViewController


- (JZHSecondViewController *)initZId:(int)zid Sid:(int)sid sname:(NSString *)name type:(int)type {
    JZHSecondViewController *jzh=[[JZHSecondViewController alloc]init];
    jzh.zid=zid;
    jzh.sid=sid;
    jzh.type=type;
    jzh.sname=name;
    return jzh;
}
//Call your menu reset method any time the view will appear
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [leftButton setSelected:NO];
    [ceview remove];
    [ceview right];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(self.type==1)
    {
     [self loadhttpdataPage:1 KeyWord:mykeyword CateId:mycateId];
    }
   
    ceview= [[JZHCEView alloc]initarr:[self.muendic allValues] viewConetroller:[JZHTabbarViewController shareInstance] TopviewStype:1];
    [ceview setCeDelete:self];
    ///侧边栏回调
    
    ceview.pusblock=^(int i){
        mycateId=[[self.muendic allKeys][i] intValue];
        [self.datadic removeAllObjects];
        [self loadhttpdataPage:1 KeyWord:mykeyword CateId:mycateId];
        [ceview right];
        };
    ceview.alldata=^(){
         [self.datadic removeAllObjects];
         [self loadhttpdataPage:1 KeyWord:@"" CateId:0];
    };
    ceview.rection=^(int i){
        if(i==1)
        {
            leftButton.selected=YES;
        }else
        {
            leftButton.selected=NO;
        }
    };
    
    
}

//You need this if you support interface rotation



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    mypage=1;
    mykeyword=@"";
    
    if(self.type==1)
    {
       
        self.scorll.hidden=NO;
        self.table.hidden=YES;
        
    }else
    {
        self.scorll.hidden=YES;
        self.table.hidden=NO;
    }
    [self loadhttpdataPage:mypage KeyWord:mykeyword CateId:mycateId];
    [self cemuen];
    //设置左按钮
    
    [self.scorll setContentSize:CGSizeMake(0, HEIGHT+100)];
    UIButton *backBut=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 12, 20)];
    [backBut setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    ;
    
    [backBut addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [backBut.titleLabel setFont:[UIFont systemFontOfSize:14]];
    UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backBut];
    [self.navigationItem setLeftBarButtonItem:backBarButton];
    
    //设置右按钮
    leftButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 15)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"leftbar_item_bg"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(showce:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:leftButton]];
    //设置导航视图title
    self.navigationItem.title=self.sname;
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for(int i=1;i<11;i++)
    {
        [arr addObject:[NSString stringWithFormat:@"sp%d.png",i]];
    }
    
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
    [self.scorll setSuperDelegate:self];
    [self.scorll hudTypeEnd];
    
}

//返回
-(void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showce:(UIButton *)but
{
    if(but.selected)
    {
        but.selected=NO;
        [ceview right];
    }else
    {
        but.selected=YES;
        [ceview left];
    }
}

- (void)bottmOffesAddData:(SuperUIScrollView *)scollview
{
    if(_datadic.count!=0)
    {
        [self loadhttpdataPage:mypage KeyWord:mykeyword CateId:mycateId];
    }else
    {
        [self loadhttpdataPage:1 KeyWord:mykeyword CateId:mycateId];

    }
}
- (void)loadhttpdataPage:(int)page KeyWord:(NSString *)keywoed CateId:(int)cateId
{
//    if(page==1)
//    {
//        [MMProgressHUD showWithStatus:@"数据加载中..."];
//    }
    
    NSLog(@"%d",page);
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.sid] ,@"brandId", keywoed,@"keyword",[NSNumber numberWithInt:page],@"page",[NSNumber numberWithInt:cateId],@"cateId",nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/topicContentList") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==HTTPReturnCodeSuccess)
        {
            if(page==1)
            {
                [_datadic removeAllObjects];
            }
            //[MMProgressHUD dismiss];
            if(!self.datadic)
            {
                self.datadic=[[NSMutableArray alloc]init];
            }
           
            
            NSLog(@"%@",data);
            NSArray *arr=[data objectForKey:@"data"];
            if(arr.count>0)
            {
                mypage++;
            }
            if(![data objectForKey:@"data"])
            {
                return ;
            }
            for(NSDictionary *dic in [data objectForKey:@"data"])
            {
               
                JZHCommodity *com=[[JZHCommodity alloc]init];
                if([NSNull null]==[dic objectForKey:@"favoriteNum"])
                {
                    com.favornum=0;
                }else
                {
                     com.favornum=[[dic objectForKey:@"favoriteNum"] intValue];
                }
               
                com.headimage=[dic objectForKey:@"image"];
                com.comid=[[dic objectForKey:@"id"] intValue];
                com.name=[dic objectForKey:@"title"];
                com.content=[dic objectForKey:@"content"];
                [_datadic addObject:com];
            }
            if(self.type==1)
            {
                self.scorll.hidden=NO;
                self.table.hidden=YES;
                [self addListView:_datadic];
            }else
            {
                self.scorll.hidden=YES;
                self.table.hidden=NO;
                [self.table reloadData];
            }
            
            
        }else
        {
           // [MMProgressHUD dismissWithError:@"暂无数据"];
            if(page==1)
            {
             [self addListView:nil];
            }
            
            [self.table reloadData];
        }
        mykeyword=@"";
        [self.scorll heiderHud];
    }];
}

///返回当前品牌的分类
- (void)cemuen
{

    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.sid]  ,@"brandId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/catList") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==HTTPReturnCodeSuccess)
        {
           
            NSLog(@"*****%@",data);
            self.muendic=[data objectForKey:@"data"];
            [ceview setArr:[self.muendic allValues]];
            [ceview.table reloadData];
            
        }else
        {
            
        }
    }];

}
//添加商品列表
- (void)addListView:(NSMutableArray *)arr
{
    
    
    //清楚scollerview上所以的子VIEW
    for(UIView * sview in [self.scorll subviews])
    {
        if([sview isKindOfClass:[UIActivityIndicatorView class]] || [sview isKindOfClass:[UILabel class]])
        {
            
        }else
        {
            [sview removeFromSuperview];
        }
        
    }
    int row=0;
    if(arr.count%2==0)
    {
        row=arr.count/2;
    }else
    {
        row=arr.count/2+1;
    }
    
    if(row*200>HEIGHT)
    {
        [self.scorll setContentSize:CGSizeMake(0, row*200+50)];
    }else
    {
        [self.scorll setContentSize:CGSizeMake(0, HEIGHT+50)];
    }
   
    int index=0;
    for(int i=0;i<row;i++)
    {
        for(int j=1;j<=2;j++)
        {
            if(i*2+j>arr.count)
            {
                return;
            }
            JZHCommodity *com=arr[index];
            
            UIView *view=[[UIView alloc]initWithFrame:CGRectMake((j-1)*145+j*10, i*180+(i+1)*15, 145, 180)];
            UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 145, 140)];
            
            [ImageCache imageUrl:com.headimage UiImageview:image];
            UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cliketop:)];
            image.userInteractionEnabled=YES;
            [image addGestureRecognizer:tap];
            [image setTag:1000+index];
            UILabel *likenum=[[UILabel alloc]initWithFrame:CGRectMake(55, 145, 100, 20)];
            [likenum setTextColor:[UIColor grayColor]];
            [likenum setText:[NSString stringWithFormat:@"有%d人喜欢",com.favornum]];
            [likenum setFont:[UIFont systemFontOfSize:12.0]];
            
            UIImageView *likeimage=[[UIImageView alloc]initWithFrame:CGRectMake(33, 150, 15, 12)];
            [likeimage setImage:[UIImage imageNamed:@"喜欢按钮"]];
            
            
            UILabel *spname=[[UILabel alloc]initWithFrame:CGRectMake(0, 170, 145, 10)];
            spname.textAlignment=NSTextAlignmentCenter;
            [spname setTextColor:[UIColor grayColor]];
            [spname setText:com.name];
            [spname setFont:[UIFont systemFontOfSize:10.0]];
            
            [view addSubview:image];
            [view addSubview:likenum];
            [view addSubview:spname];
            [view addSubview:image];
            [view addSubview:likeimage];
            [self.scorll addSubview:view];
            index++;
            if(index>arr.count)
            {
                return;
            }
        }
        
    }
}


#pragma mark----侧边栏代理-----
- (void)CESo:(NSString *)str
{
    [self.datadic removeAllObjects];
    
    [self loadhttpdataPage:1 KeyWord:str CateId:0];
}
- (void)cliketop:(UITapGestureRecognizer *)tap
{
    JZHCommodity *comm=_datadic[tap.view.tag-1000];
  
    [self.navigationController pushViewController:[[JZHProductDetailsViewController alloc]initCommdodity:comm] animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-------TableView代理----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    if(self.type==1)
    {
        return 0;
    }
    return self.datadic.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 290;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str=@"JZHSecond";
    JZHSecondTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:str ];
    if(!cell)
    {
        cell=[[NSBundle mainBundle]loadNibNamed:@"JZHSecondTableViewCell" owner:self options:nil][0];
        cell.but=^(int i){
            
            NSLog(@"%d",indexPath.row);
            JZHCommodity *com=[[JZHCommodity alloc] init];
            NSLog(@"%@",self.datadic);
            com=self.datadic[indexPath .row];
            NSLog(@"%d",com.comid);
            [self.navigationController pushViewController:[[JZHNoProductViewController alloc] initcom:com] animated:YES];
        };
    }
    [cell addcelldata:self.datadic [indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}





@end
